package com.ycy.leetcode.offer;


import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class offer29 {

  /**
   * 顺时针打印 矩阵
   * <p>
   * {
   * {1,2,3,4}
   * {5,7,8,9}
   * {11,12,13,14}
   * }
   *
   * @param args
   */
  public static void main(String[] args) {

    int[][] arr = {
            {1, 2, 3, 4},
            {5, 7, 8, 9},
            {11, 12, 13, 14}
    };
    System.out.println(arr[2][2]);

    /*
    t
  l    r
    b
    边界下标 (边界本身可访问)
     */
    int x = arr[0].length; // 第二维度
    int y = arr.length; //第一维度

    int t = 0;
    int r = x - 1;
    int b = y - 1;
    int l = 0;

    int ex = -1;

    List<Integer> list = Lists.newArrayList();

    while (true) {
      //top 左到右
      if (l > r) break;
      for (int i = l; i <= r; i++) {
        list.add(arr[t][i]);
      }
      t++;
      //right 上到下
      if (t > b) break;
      for (int i = t; i <= b; i++) {
        list.add(arr[i][r]);
      }
      r--;
      //button 右到左
      if (l > r) break;
      for (int i = r; i >= l; i--) {
        list.add(arr[b][i]);
      }
      b--;
      //left 下到上
      if (t > b) break;
      for (int i = b; i >= t; i--) {
        list.add(arr[i][l]);
      }
      l++;
    }
    System.out.println(Arrays.asList(list));

  }

  @Test
  public void test(){
    int [][] ma = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
    int[] ints = spiralOrder(ma);
    System.out.println(Arrays.toString(ints));

  }

  public int[] spiralOrder(int[][] matrix) {
    int t = 0;
    int l = 0;
    int r = matrix[0].length - 1;
    int b = matrix.length - 1;

    int cur = 0;
    int res[] = new int[(r + 1) * (b + 1)];

    while (true) {
      if (l > r) break;
      for (int k = l; k <= r; k++) {
        res[cur++] = matrix[t][k];

      }
      t++;

      if (t > b) break;
      for (int k = t; k <= b; k++) {
        res[cur++] = matrix[k][r];
        System.out.print(matrix[k][r] + ",");

      }
      r--;

      if (l > r) break;
      for (int k = r; k >= l; k--) {
        res[cur++] = matrix[b][k];

      }
      b--;


      if (t > b) break;
      for (int k = b; k >= t; k--) {
        res[cur++] = matrix[k][l];
      }
      l++;
    }
    return res;

  }


}
